package com.tang.net;


import android.util.Log;

import com.tang.user.UserInfoManager;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import io.reactivex.schedulers.Schedulers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;


/**
 * CreateTime: 2016-04-11上午9:48
 * Author: wjkjinke00@126.com
 * Description:
 */
public final class NetClient {

    private static final int TIME_OUT = 30 * 1000;
    private static final String TEST = "https://dev.auscult.cn:9181/api/rest/v2/";
//    private static final String TEST = "https://dev.auscult.cn:9180/api/rest/v2/";
    public static final String IMG_URL = "https://dev.auscult.cn/v2/files/";

    public static final String BASE_URL = TEST;

    private static final Retrofit mRetrofit;

    static {
        mRetrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(getHttpClient())
                .addConverterFactory(MyGsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
                .build();
    }

    private NetClient() {
    }

    public static <Api> Api getInstance(Class<Api> clazz) {
        return mRetrofit.create(clazz);
    }

    private static OkHttpClient getHttpClient() {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(TIME_OUT, TimeUnit.MILLISECONDS)
                .readTimeout(TIME_OUT, TimeUnit.MILLISECONDS)
                .writeTimeout(TIME_OUT, TimeUnit.MILLISECONDS)
                .addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                    @Override
                    public void log(String message) {
                        Log.e("OKHTTP", message);
                    }
                }).setLevel(HttpLoggingInterceptor.Level.BODY))
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request.Builder builder = chain.request().newBuilder();
//                        builder.addHeader("Platform", "2");
                        if (UserInfoManager.getInstance().getToken() != null && !UserInfoManager.getInstance().getToken().isEmpty()) {
                            Log.e("access-token", UserInfoManager.getInstance().getToken());
                            builder.addHeader("access-token", UserInfoManager.getInstance().getToken());
                        } else {
                            builder.addHeader("access-token", "");
                        }
                        return chain.proceed(builder.build());
                    }
                })
                .build();
        return client;
    }

}
